package com.cj.elasticsearch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cj.elasticsearch.config.ElasticsearchConfig;
import com.cj.elasticsearch.entity.User;
import com.cj.elasticsearch.service.ElasticsearchService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/11/6 19:10
 */
@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public IndexResponse indexData() {
        IndexRequest indexRequest = new IndexRequest("users");
        // 数据的id
        indexRequest.id("user");
        User user = new User();
        user.setUserName("张三");
        user.setGender("男");
        user.setAge(18);
        String jsonString = JSONObject.toJSONString(user);
        indexRequest.source(jsonString, XContentType.JSON);

        // 保存
        IndexResponse indexResponse = null;
        try {
            indexResponse = restHighLevelClient.index(indexRequest, ElasticsearchConfig.COMMON_OPTIONS);
        } catch (Exception e) {
        }
        return indexResponse;
    }
}
